
class PagerThing < Thing

  attribute :content_type
  attribute :items_per_page
  attribute :template_name

  def recieve e
    ['items_per_page'].each { |a|
      if e.params[form_id a]
        self.send(a+'=', e.params[form_id a].to_i)
      end
    }

    ['content_type', 'template_name'].each { |a|
      if e.params[form_id a]
        self.send(a+'=', e.params[form_id a])
      end
    }

    if e.params[form_id(:adding)]
      item = nil
      if item_id = e.params[form_id(:item_id)]
        item = content_class.get! item_id.to_i
      else
        ContentTemplate.all().each { |t|
          if t.template_class == content_type
            raise 'More than one item found!' if item
            item = t.clone_thing
          end
        }
      end

      e.params['save'] = true
      item.recieve e
      @item = item
    end
  end

  def content_template
    item = nil
    ContentTemplate.all(:template_class => content_type).each { |t|
        raise 'More than one item found!' if item
        item = t
      }
    item
  end

  def creator e
    s = "<p>Stránkuj: "

    templates = Hash[*ContentTemplate.all.collect { |t|
          [t.template_class, t]
        }.flatten]

    types = Hash[*ContentTemplate.all.collect { |t|
          [t.template_class, t.template_title]
        }.flatten]


    content_sel = Select.new({
        :name => form_id(:content_type)},
        types
      )

    content_sel.value = content_type

    s << content_sel.to_s


    s << ", Po: "

    s << Element.new(
        :input,
        :name => form_id(:items_per_page),
        :value => items_per_page,
        :size => 3
      ).to_s




    if content_class
      s << "<p>šablona: "

      template = Select.new({
          :name => form_id(:template_name)},
          [["", "žádná"]] +
          templates[content_type].children.select {|ch|
            ch.is_a? TemplateThing
          }.map { |t|
            [t.name, t.name]
          }
        )
      template.value = template_name
      s << template.to_s
      s << '</p>'
    end


    if content_class
      content_template.visit { |t|
        puts t.class
        if t.respond_to? :filters
          p t
          select = el(:select)
          select.options = t.filters
          s << select.to_s
        end
      }
    end

    

    if content_class
      s << Element.new(
        :input,
        :type => :submit,
        :name => form_id(:add),
        :value => '+ '+types[content_type]
      ).to_s
    end


    if e.params[form_id(:add)] ||  e.params[form_id(:adding)]
      s << "<div class=\"pagerInner\">"
      #item = ContentThing.all() :content_class.new.
      item = @item

      if !item
        if item_id = e.params[form_id(:item_id)]
          item = content_class.get! item_id
        else
          ContentTemplate.all.each { |t|
            if t.template_class == content_type
              raise 'More than one item found!' if item
              item = t.clone_thing
              if item.respond_to? :place=
                item.place = root.identity
              end
            end
          }
        end
      end

      if !item.new?
        s << Element.new(
            :input,
            :type => :hidden,
            :name => form_id(:item_id),
            :value => item.id
          ).to_s
      end
      
      #item.default_content
      s << item.creator(e).to_s
      s << Element.new(
          :input,
          :type => :hidden,
          :name => form_id(:adding)
        ).to_s
      s << "</div>"
    end


    items = Element.new(:div, :class => "pager-items")
    list(1) { |i|
      item_el = Element.new(
        :div,
        :class => 'item'
      )
      item_el << i.title
      item_el << SubmitButton.new(:value => 'smaž')

      items << item_el
    }
    s << items.to_s

    s + '</p>'
  end

  def render e
    s = ''

    template = nil

    if (t = template_name) && template_name != ''
      template = content_template.children.select { |ch|
        (ch.is_a? TemplateThing) && (ch.name == t)
      }.first
      #return "template " + t + " " + template.inspect
    end


    #page = e.params['page']
    if content_class
      page = e.env[:unprocessed_tail].last.to_i || 1
      content = content_class.all(query_filters)
      len = content.length
      if page <= 0 || page > len
        page = 1
      end
      list(page) { |c|
        if !template
          s << (c.wrap_render e)
        else
          s << (template.render c, e)
        end
      }
      s << pager(e, page, content)
    end
#    s << pager
    s
  end


  def query_filters
    f = {}
    if content_class
      if content_class.new.respond_to?(:place) && self.root.respond_to?(:breadth_first)
        root = self.root
        f[:place] = [root.identity]
        root.breadth_first { |child|
          f[:place] << child.identity
        }
      end
    end
    f
  end

  def pager e, at_page, content
    return '' if !content_class
    len = content.length
    s = ''
    s << (1..(len/items_per_page).ceil).collect { |page|
      if page == at_page
        Element.new(:b, page.to_s, :class => 'actualPage')
      elsif page == 1
        Element.new(:a, page.to_s, :href => e.sublink(''))
      else
        Element.new(:a, page.to_s, :href => e.sublink(page.to_s))
      end
    }.join(", ")
    '<p>'+s+'</p>'
  end

  def list page = 1, &block
    if content_class
      content_class.all(query_filters.merge :offset => page.to_i-1, :limit => items_per_page.to_i).each(&block)
    end
  end

  def content_class
    if content_type && content_type != ''
      begin
        self.class.to_const content_type
      rescue
        warn "Could not get class #{content_type}."
        nil
      end
    end
  end

end
